package com.mong.demo.service;

import com.mong.demo.pojo.User;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void saveUser(User user) {
        mongoTemplate.save(user);
    }

    @Override
    public User findUserByUserName(String userName) {
        Query query  = new Query(Criteria.where("username").is(userName));
        return mongoTemplate.findOne(query,User.class);
    }

    @Override
    public long updateUser(User user) {
        Query query = new Query(Criteria.where("id").is(user.getUid()));
        Update update = new Update().set("username",user.getUsername()).set("pwd",user.getPwd());
        UpdateResult updateResult = mongoTemplate.updateFirst(query,update,User.class);
        if (updateResult != null){
            return updateResult.getModifiedCount();
        }
        return 0;
    }

    @Override
    public void deleteUserById(Long id) {
       Query query = new Query(Criteria.where("uid").is(id));
       mongoTemplate.remove(query,User.class);
    }
}
